package com.haiheng.moudule_visualinventoryrobot.fragment

import android.annotation.SuppressLint
import android.content.ContentValues
import android.graphics.drawable.Drawable
import android.hardware.usb.UsbDevice
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.rabbitmq.MQSettings
import com.haiheng.library_base.rabbitmq.RabbitmqHelper
import com.haiheng.library_base.utils.DateUtils
import com.haiheng.moudule_visualinventoryrobot.R
import com.haiheng.moudule_visualinventoryrobot.databinding.DemoFragmentBinding
import com.haiheng.moudule_visualinventoryrobot.dialog.MultiCameraDialog
import com.jiangdg.ausbc.MultiCameraClient
import com.jiangdg.ausbc.base.BaseBottomDialog
import com.jiangdg.ausbc.callback.ICameraStateCallBack
import com.jiangdg.ausbc.callback.ICaptureCallBack
import com.jiangdg.ausbc.camera.CameraUVC
import com.jiangdg.ausbc.utils.ToastUtils
import com.jiangdg.ausbc.widget.AspectRatioTextureView
import com.jiangdg.ausbc.widget.IAspectRatio
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/2/27 0027
 * @Version: 1.0
 */
class DemoFragment: CustomCameraFragment(){
    private var TAG:String = "DemoFragment"
    private lateinit var mViewBinding: DemoFragmentBinding
    private var mMultiCameraDialog: MultiCameraDialog? = null
    private var deviceList: MutableList<UsbDevice> = mutableListOf()

    private var currentIndex = 0
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mViewBinding = DemoFragmentBinding.inflate(inflater, container, false)
        return mViewBinding.root
    }

    override fun onCameraState(
        self: MultiCameraClient.ICamera,
        code: ICameraStateCallBack.State,
        msg: String?
    ) {
        LogUtils.d("onCameraState $code code${msg}")

        when (code) {
            ICameraStateCallBack.State.OPENED -> handleCameraOpened()
//            ICameraStateCallBack.State.CLOSED -> handleCameraClosed()
//            ICameraStateCallBack.State.ERROR -> handleCameraError(msg)
        }
    }


    override fun initView() {
        super.initView()
        loadAnimTest()
        LogUtils.d("initView")
        mViewBinding.testCap.setOnClickListener {
            captureImage()
        }

        mViewBinding.testMulti.setOnClickListener {
            unRegisterMultiCamera()
            mMultiCameraDialog = MultiCameraDialog()
            mMultiCameraDialog?.setOnDismissListener(object : BaseBottomDialog.OnDismissListener {
                override fun onDismiss() {
                    registerMultiCamera()
                }
            })
            mMultiCameraDialog?.show(childFragmentManager, "multiRoadCameras")
        }
        mViewBinding.swichCamele.setOnClickListener {
            getCurrentCamera()?.let {strategy ->
                LogUtils.d("${TAG} getCurrentCamera strategy")
                if (strategy is CameraUVC) {
                    showUsbDevicesDialog(getDeviceList(), strategy.getUsbDevice())
                }
            }
        }
        mViewBinding.swichResolution.setOnClickListener {
            showResolutionDialog()
        }
        mViewBinding.testMq.setOnClickListener {
            testmq()
        }
        mViewBinding.testSendMsg.setOnClickListener {
            sendMsg()
        }
    }

    override fun getCameraView(): IAspectRatio? {
        return AspectRatioTextureView(requireContext())
    }

    override fun getCameraViewContainer(): ViewGroup? {
        return mViewBinding.cameraViewContainer

    }

    override fun initViewModel(): BaseViewModel? {

        return null
    }

    override fun initLoad() {

    }

    private fun handleCameraOpened() {
        GlobalScope.launch {
            delay(3000)
            captureImage()
        }
        deviceList = getDeviceList() ?: mutableListOf()
    }

    private fun captureImage() {
        captureImage(object : ICaptureCallBack {
            override fun onBegin() {
                LogUtils.d("拍照 onBegin")
            }

            override fun onError(error: String?) {
                ToastUtils.show(error ?: "未知异常")

            }

            override fun onComplete(path: String?) {
                LogUtils.d("拍照完成：${path}")
                currentIndex++
                // TODO: 连续拍照
//                startCaptureCycle()
            }
        },getImagePath(getCurrentCamera()?.device))
    }

    private fun getImagePath(device: UsbDevice?): String {
        LogUtils.d("获取当前摄像头保存路径")
        val currentDate = DateUtils.dateToString(DateUtils.DATE_FORMAT_4,Date())
        val deviceName = device?.productName?.replace(" ", "_")
        val fileName = "${deviceName}_$currentDate.jpg"
        LogUtils.d("fileName:${fileName}")
        // 创建日期命名的文件夹
        val imageDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), currentDate)
        imageDir.mkdirs()

        // 将图片保存到文件夹中
        val file = File(imageDir, fileName)
//        imagePath?.let { sourcePath ->
//            val sourceFile = File(sourcePath)
//            sourceFile.copyTo(file, true)
//        }

        LogUtils.d("要保存的路径：${file.absolutePath}")
        return file.absolutePath
    }
    fun loadAnimTest(){
        Glide.with(this).load(R.mipmap.ic_loading_anim) .addListener(object : RequestListener<Drawable?> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: com.bumptech.glide.request.target.Target<Drawable?>?,
                isFirstResource: Boolean
            ): Boolean {
//                mViewBinding.ivTestAnim.setImageResource(defaultIcon)
                return false
            }

            override fun onResourceReady(
                resource: Drawable?,
                model: Any?,
                target: Target<Drawable?>?,
                dataSource: DataSource?,
                isFirstResource: Boolean
            ): Boolean {

                if (resource is WebpDrawable) {
                    //循环
                    resource.loopCount = -1
                }
                return false
            }
        }).into(mViewBinding.ivTestAnim)
    }


    @SuppressLint("CheckResult")
    private fun showUsbDevicesDialog(usbDeviceList: MutableList<UsbDevice>?, curDevice: UsbDevice?) {
        if (usbDeviceList.isNullOrEmpty()) {
            ToastUtils.show("Get usb device failed")
            return
        }
        val list = arrayListOf<String>()
        var selectedIndex: Int = -1
        for (index in (0 until usbDeviceList.size)) {
            val dev = usbDeviceList[index]
            val devName = if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP && !dev.productName.isNullOrEmpty()) {
                "${dev.productName}(${curDevice?.deviceId})"
//                dev.deviceName
            } else {
                dev.deviceName
            }
            val curDevName = if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP && !curDevice?.productName.isNullOrEmpty()) {
                "${curDevice!!.productName}(${curDevice.deviceId})"
//                curDevice?.deviceName
            } else {
                curDevice?.deviceName
            }
            if (devName == curDevName) {
                LogUtils.d("${TAG} curDevName:${curDevName}")
                selectedIndex = index
            }
            list.add(devName)
        }
        MaterialDialog(requireContext()).show {
            listItemsSingleChoice(
                items = list,
                initialSelection = selectedIndex
            ) { dialog, index, text ->
                if (selectedIndex == index) {
                    return@listItemsSingleChoice
                }
                switchCamera(usbDeviceList[index])
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun showResolutionDialog() {
        getAllPreviewSizes().let { previewSizes ->
            if (previewSizes.isNullOrEmpty()) {
                ToastUtils.show("Get camera preview size failed")
                return
            }
            val list = arrayListOf<String>()
            var selectedIndex: Int = -1
            for (index in (0 until previewSizes.size)) {
                val w = previewSizes[index].width
                val h = previewSizes[index].height
                getCurrentPreviewSize()?.apply {
                    if (width == w && height == h) {
                        selectedIndex = index
                    }
                }
                list.add("$w x $h")
            }

            MaterialDialog(requireContext()).show {
                listItemsSingleChoice(
                    items = list,
                    initialSelection = selectedIndex
                ) { dialog, index, text ->
                    if (selectedIndex == index) {
                        return@listItemsSingleChoice
                    }
                    updateResolution(previewSizes[index].width, previewSizes[index].height)
                }
            }
        }
    }

    private fun startCaptureCycle() {
        // 检查索引是否越界
        if (currentIndex < deviceList.size) {
            // 获取当前设备
            val device = deviceList[currentIndex]
            // 拍照
            LogUtils.d("切换${device.productName}进行拍照")
            switchCamera(device)
//            captureImage()
        } else {
            // 设备列表中的设备已经全部拍照完成，重新开始拍照循环
            currentIndex = 0
//            startCaptureCycle()
        }
    }


    fun testmq(){
        RabbitmqHelper.subscribe() { message ->
            // 处理收到的消息
            LogUtils.d("${TAG} Received message: $message")
        }
    }

    fun sendMsg(){
        RabbitmqHelper.publish("测试发送消息")
    }
}